<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <table>
        <tr>
            <td>用户名</td>
            <td>年龄</td>
        </tr>

    </table>
    姓名: <input type="text" name="username" id=""/><br/>
    年龄: <input type="text" name="age" id=""/><br/>
    <input type="button" onclick="reg()" value="注册"/>
<script>
    function reg(){
        var username = document.querySelector('input[name=username]').value;
        var age = document.querySelector('input[name=age]').value;
        var user = {
            username:username,
            age:age
        }
        //1.创建ajax
        var xhr = new XMLHttpRequest();
        //设置响应类型为json
        xhr.reponseType = 'json';
        //2.open
        xhr.open('POST','/reg',true);
        //3.注册异步监听
        xhr.onreadystatechange = function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
//                    var users = xhr.response;
                    var users = JSON.parse(xhr.responseText);
                    var str = '';
                    for(var i=0;i<users.length;i++){
                        str += '<tr>';
                        str += '<td>';
                        str += users[i].username;
                        str += '</td>';
                        str += '<td>';
                        str += users[i].age;
                        str += '</td></tr>';
                    }
                    document.querySelector('table').innerHTML += str;
                }
            }
        }
        //4.发送
        xhr.send(JSON.stringify(user));
    }


</script>
</body>
</html>